package com.lixia.lxframework.framework.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

/**
 * 功能描述:
 * <p> 读取properties文件
 * Created by Mr.wang on 2017/9/16 19:55.
 */
public class PropertiesUtils {

    private static final Logger log = LoggerFactory.getLogger(PropertiesUtils.class);

    /**
     * 读取配置文件properties
     *
     * @param propertiesPath 文件加载路径
     * @return
     */
    public static Map<String, String> loadProps(String propertiesPath) {
        Properties properties = new Properties();
        Map<String, String> resultMap = new HashMap<>(16);
        try {
            FileInputStream inputStream = new FileInputStream(propertiesPath);
            //加载属性列表
            properties.load(inputStream);
            Iterator<String> iterator = properties.stringPropertyNames().iterator();
            while (iterator.hasNext()) {
                String key = iterator.next();
                String value = properties.getProperty(key);
                resultMap.put(key, value);
                System.out.println("key:[" + key + "]:::::::::>value:[" + value + "]");
            }
            inputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            log.error("FilePath...[" + propertiesPath + "]...FileNotFoundException.Cause By " + e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            log.error("IOException.Cause By " + e.getMessage());
        }
        return resultMap;
    }

    /**
     * 保存属性到properties文件
     *
     * @param propertiesPath 输出文件路径
     */
    public static void setProps(String propertiesPath, Map<String, String> map, boolean appendFlag) {
        try {
            FileOutputStream out = new FileOutputStream(propertiesPath, appendFlag);
            Properties properties = new Properties();
            for (Map.Entry<String, String> entity : map.entrySet()) {
                String key = entity.getKey();
                String value = entity.getValue();
                properties.setProperty(key, value);
                properties.store(out, "The New properties file");
            }
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            log.error("FilePath...[" + propertiesPath + "]...FileNotFoundException.Cause By " + e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            log.error("IOException.Cause By " + e.getMessage());
        }
    }

}
